import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login.vue'
import Layout from '../views/layout.vue'
import Articles from '../views/articles.vue'
import Home from '../views/home.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '', component: Home },
      { path: '/articles', component: Articles }
    ]
  }
]

const router = new VueRouter({
  routes
})

const vipPages = ['/', '/articles']
router.beforeEach((to, from, next) => {
  const tokenStr = localStorage.getItem('token')
  if (vipPages.includes(to.path) && !tokenStr) {
    next('/login')
  } else if (to.path === '/login' && tokenStr) {
    next(from.path)
  } else {
    next()
  }
})

export default router
